package com.zisu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/9/4 15:10
 */
@Component
public class MyLB implements LoadBalance{
    //atomicInteger 为 第几次 访问
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncreament(){
        int current;
        int next;
        do{
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0:current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*****next:"+next);

        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncreament() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
